//
//  BanBu_MagicDetailViewController.m
//  BanBu
//
//  Created by Wang Xj on 13-10-29.
//
//

#import "BanBu_MagicDetailViewController.h"
#import "BanBu_MagicFaceCell.h"
#import "BanBu_ImageView.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "TKLoadingView.h"
#import "SCGIFImageView.h"
#import "BanBu_NavButton.h"
#import "BanBu_ChatViewController.h"
#import "BanBu_ThemeManager.h"
#import "ETActivityIndicatorView.h"

@interface BanBu_MagicDetailViewController ()

@end

@implementation BanBu_MagicDetailViewController
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
    
    BanBu_NavButton *actionButton=[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    actionButton.position = ButtonPositionRight;
    actionButton.frame=CGRectMake(0, 7, 50, 30);
    
    [actionButton addTarget:self action:@selector(downloadMagicFace:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView * imageview = [[UIImageView alloc]init];
    imageview.frame = CGRectMake(12.5, 2.5, 25, 25);
    imageview.image = [UIImage imageNamed:@"cache_download.png"];
    
    [actionButton addSubview:imageview];
    
    self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithCustomView:actionButton]autorelease];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [self.bigImageBgView removeFromSuperview];
    ThemeManager.magicFaceController = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceilf(self.magicUrlList.count/4.0);
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    BanBu_MagicFaceCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[BanBu_MagicFaceCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
        [cell addGesture];
    }
    
    NSMutableArray * imageArray = [NSMutableArray arrayWithCapacity:1];
    
    for(int i = 0; i<4 && (indexPath.row*4+i)<self.magicUrlList.count;i++)
    {
        [imageArray addObject:[self.magicUrlList objectAtIndex:(indexPath.row*4 + i)]];
    }
    
    [cell clearImage];
    [cell setImageUrl:imageArray];
    
    return cell;
}

-(void)menuShow:(UIView *)sender tableCell:(BanBu_MagicFaceCell *)sendert
{
    if (self.bigImageBgView)
    {
        return;
    }
    NSString * bigImageUrl = nil;
    NSString * smallImageUrl = nil;
    
    switch (sender.tag)
    {
        case 1:
        {
            bigImageUrl = sendert.firstBigGifUrl;
            smallImageUrl = sendert.firstSmallGifUrl;
        }
            break;
        case 2:
        {
            bigImageUrl = sendert.secondBigGifUrl;
            smallImageUrl = sendert.secondSmallGifUrl;
        }
            break;
        case 3:
        {
            bigImageUrl = sendert.thirdBigGifUrl;
            smallImageUrl = sendert.thirdSmallGifUrl;
        }
            break;
        case 4:
        {
            bigImageUrl = sendert.fourthBigGifUrl;
            smallImageUrl = sendert.fourthSmallGifUrl;
        }
            break;
        default:
            return;
            break;
    }

    if (bigImageUrl == nil || smallImageUrl == nil)
    {
        return;
    }
    self.bigGifUrl = bigImageUrl;
    self.smallImageUrl = smallImageUrl;
   
    if([FileManager fileExistsAtPath:[AppComManager pathForMsgMedia:bigImageUrl]])
    {
        [self setBackgroundView:[NSDictionary dictionaryWithObjectsAndKeys:bigImageUrl,@"oldImageUrl", nil]];
    }
    else
    {//下载大图片
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"isDownloading", nil) activityAnimated:YES];
        self.navigationController.view.userInteractionEnabled = NO;
        [AppComManager getBanBuMedia:bigImageUrl delegate:self];
    }
}

//发送魔法表情，“mg”
-(void)sendMsg
{
    if ([FileManager fileExistsAtPath:[AppComManager pathForMsgMedia:self.bigGifUrl]])
    {
        NSMutableDictionary * sendDic = [NSMutableDictionary dictionaryWithCapacity:2];
        [sendDic setValue:self.bigGifUrl forKey:@"bigGifUrl"];
        [sendDic setValue:@"gif" forKey:@"fileType"];
        [sendDic setValue:self.smallImageUrl forKey:@"smallImageUrl"];
        [sendDic setValue:[NSNumber numberWithInt:ChatCellTypeFullScreenGif] forKey:KeyType];
        [sendDic setValue:@"mg" forKey:KeyShowFrom];
        
      
        [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
        [self cancelDownloadOrHidden];
        [self popToChat];
    }
}

-(void)popToChat
{
    [self.navigationController popToViewController:self.chat animated:YES];
}

-(void)setBackgroundView:(NSDictionary *)resDic
{
    self.bigImageBgView = [[[UIView alloc]initWithFrame:CGRectZero] autorelease];
    
    //加背景图
    self.bgview = [[UIView alloc]init];
    self.bgview.backgroundColor = [UIColor blackColor];
    self.bgview.alpha = 0.5;
    [self.bigImageBgView addSubview:self.bgview];
    
    BanBu_NavButton * btn_send = [[BanBu_NavButton alloc]initWithButtonType:UIButtonCreatTypeCustomBtn];
    btn_send.position = ButtonPositionRight;
    btn_send.frame=CGRectMake(10, __MainScreen_Height-45, 300, 44);
    [btn_send setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    [btn_send addTarget:self action:@selector(sendMsg) forControlEvents:UIControlEventTouchUpInside];
    btn_send.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.bigImageBgView addSubview:btn_send];
    
    self.bigImageBgView.backgroundColor = [UIColor clearColor];
    self.bigImageBgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelDownloadOrHidden:)];
    [self.bigImageBgView addGestureRecognizer:tap];
    [tap release];
    
    self.bigImageBgView.center = self.navigationController.view.center;
    
    //加载gif图
    [self showBigGifDownload:resDic];

    CGSize size = self.bigGif.image.size;
    if (size.width>320)
    {
        size.height = size.height*320/size.width;
        size.width = 320;
    }
    
    [self.navigationController.view addSubview:self.bigImageBgView];
    
        [UIView animateWithDuration:0.5
                     animations:^{
                         self.bigImageBgView.center = self.navigationController.view.center;
                         self.bigImageBgView.frame = __MainScreenFrame;
                         self.bgview.frame = self.bigImageBgView.frame;
                         self.bigGif.bounds = CGRectMake(0, 0, size.width, size.height);
                         self.bigGif.center = self.bigImageBgView.center;
                     }
                     completion:^(BOOL finished) {
                         self.bigGif.center = self.bigImageBgView.center;
                     }];
}

//显示大图，并隐藏小图
-(void)showBigGifDownload:(NSDictionary *)resDic
{
    NSString * newImagePath = [AppComManager pathForMsgMedia:[resDic valueForKey:@"oldImageUrl"]];
    self.bigGif = [[[SCGIFImageView alloc]initWithFrame:CGRectZero] autorelease];
    
    self.bigGif.gifFile = newImagePath;
    [self.bigImageBgView addSubview:self.bigGif];
}

- (void)banbuDownloadRequest:(NSDictionary *)resDic didFinishedWithError:(NSError *)error
{
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0.0];
    
    if(error)
    {
        if([error.domain isEqualToString:BanBuDataformatError])
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        else
        {
            [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        }
        return;
    }
    
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        //将下载的大图转移到消息缓存文件的文件夹
        NSString * oldImagePath = [resDic valueForKey:@"oldImageUrl"];
        oldImagePath = [AppComManager pathForMedia:oldImagePath];
        
        NSString * newImagePath = [AppComManager pathForMsgMedia:[resDic valueForKey:@"oldImageUrl"]];
                
        [FileManager moveItemAtPath:oldImagePath toPath:newImagePath error:nil];
        
        [self setBackgroundView:resDic];
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[MyAppDataManager IsInternationalLanguage:[resDic valueForKey:@"error"]] activityAnimated:NO duration:1.0];
    }
}

-(void)cancelDownloadOrHidden
{
    [AppComManager cancalHandlesForObject:self];
    [self.bigImageBgView removeFromSuperview];
    self.bigImageBgView = nil;
}

-(void)cancelDownloadOrHidden:(UITapGestureRecognizer *)tap
{
    [AppComManager cancalHandlesForObject:self];
    
        [UIView animateWithDuration:0.5
                     animations:^{
                         
                         self.bigImageBgView.bounds = CGRectMake(0, 0, 0, 0);
                         self.bgview.frame = CGRectMake(0, 0, 0, 0);
                         self.bigGif.frame = CGRectMake(0, 0, 0, 0);
                         
                     }
                     completion:^(BOOL finished) {
                         [self.bigImageBgView removeFromSuperview];
                         self.bigImageBgView = nil;
                     }];
}


-(void)downloadMagicFace:(BanBu_NavButton *)sender
{
    if ([self.view viewWithTag:323232])
    {
        return;
    }
    else
    {
        CGRect rect = CGRectMake(0, 0, 100, 100);
        
        self.tfIndic = [[[ETActivityIndicatorView alloc] initWithFrame:rect andColor:[UIColor grayColor]] autorelease];
        self.tfIndic.center = self.navigationController.view.center;
        self.tfIndic.tag = 323232;
        [self.view addSubview:self.tfIndic];
        [self.tfIndic startAnimating];
    }
    //下载表情包
    ThemeManager.magicFaceController = self;
    NSString *cachePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
    NSString *path  = [cachePath stringByAppendingPathComponent:@"MsgImageCache"];
 
    
    if (![FileManager fileExistsAtPath:path])
    {
        [FileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    [ThemeManager downLoadMagicfaceWithURL:[NSMutableArray arrayWithArray:self.magicUrlList] atIndex:0];
}

//移除下载显示
-(void)dismissActive
{
    if (self.tfIndic)
    {
        [self.tfIndic stopAnimating];
        [self.tfIndic removeFromSuperview];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 1:
        {
            [ThemeManager downLoadMagicfaceWithURL:[NSMutableArray arrayWithArray:self.magicUrlList] atIndex:0];
        }
            break;
            
        default:
            [self dismissActive];
            break;
    }
}

-(void)dealloc
{
    [_tfIndic release],_tfIndic = nil;
    [_bgview release],_bgview = nil;
    [_bigGif release],_bigGif = nil;
    [_bigGifUrl release],_bigGifUrl = nil;
    [_imageView release],_imageView = nil;
    [_smallImageUrl release],_smallImageUrl = nil;
    [_magicUrlList release],_magicUrlList = nil;
    [_bigImageBgView release],_bigImageBgView = nil;
    [super dealloc];
}
@end
